import { defineStore } from 'pinia'
import { ref } from 'vue'
import * as workstationApi from '@/api/workstation'

export const useWorkstationStore = defineStore('workstation', () => {
  const workstations = ref([])
  const currentWorkstation = ref(null)
  const searchResults = ref([])

  /**
   * 获取工位列表
   * @param {string} status - 工位状态筛选 (可选)
   */
  const fetchWorkstations = async (status = null) => {
    const response = await workstationApi.getWorkstations(status)
    workstations.value = response.data.items
    return response.data
  }

  /**
   * 根据ID获取工位详情
   * @param {number} id - 工位ID
   */
  const fetchWorkstationById = async (id) => {
    const response = await workstationApi.getWorkstationDetail(id)
    currentWorkstation.value = response.data
    return response.data
  }

  /**
   * 搜索工位
   * @param {string} keyword - 搜索关键词
   * @param {number} limit - 返回数量限制
   */
  const searchWorkstations = async (keyword, limit = 10) => {
    const response = await workstationApi.searchWorkstations(keyword, limit)
    searchResults.value = response.data.items
    return response.data
  }

  /**
   * 同步工位信息
   * @param {string} name - 工位名称
   */
  const syncWorkstation = async (name) => {
    const response = await workstationApi.syncWorkstation(name)
    // 同步成功后，将新工位添加到列表
    workstations.value.push(response.data)
    return response.data
  }

  /**
   * 执行工位操作
   * @param {number} id - 工位ID
   * @param {string} action - 操作类型
   * @param {object} parameters - 操作参数
   */
  const executeAction = async (id, action, parameters = null) => {
    const response = await workstationApi.executeWorkstationAction(id, action, parameters)
    // 操作成功后，刷新工位信息
    await fetchWorkstationById(id)
    return response.data
  }

  /**
   * 获取操作历史
   * @param {number} id - 工位ID
   * @param {object} params - 查询参数
   */
  const fetchActionHistory = async (id, params = {}) => {
    const response = await workstationApi.getActionHistory(id, params)
    return response.data
  }

  return {
    workstations,
    currentWorkstation,
    searchResults,
    fetchWorkstations,
    fetchWorkstationById,
    searchWorkstations,
    syncWorkstation,
    executeAction,
    fetchActionHistory
  }
})

